//
//  DLWWeChatShareManager.m
//  DGGBaseSDK
//  分享统一处理类
//  Created by DL_hzk on 2018/6/7.
//  Copyright © 2018年 DL. All rights reserved.
//

#import "DLWWeChatShareManager.h"
#import "WWKApiObject.h"
#import "WWKApi.h"
#import <UShareUI/UShareUI.h>
#import "DLWWeChatShareMsgModel.h"
#import "DLWWeChatShareConfig.h"

@interface DLWWeChatShareManager()<UMSocialShareMenuViewDelegate, WWKApiDelegate>

@property (nonatomic, strong) DLWWeChatShareMsgModel *shareMsgModel;
@property (nonatomic, assign) DLWWeChatShareCustomPlatformType currentType;

@end

@implementation DLWWeChatShareManager

+ (instancetype)sharedInstance{
    static DLWWeChatShareManager *_sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[DLWWeChatShareManager alloc] init];
    });
    return _sharedInstance;
}

- (void)dl_shareToWX:(UMSocialPlatformType)platformType
         withMediaURL:(NSString *)url
             thumbURL:(NSString *)thumbURL
                title:(NSString *)title
              content:(NSString *)content{
    if(!self.delegate){
        UIWindow *rootWindow = [UIApplication sharedApplication].keyWindow;
        if([rootWindow.rootViewController valueForKey:@"mainViewController"] && [[rootWindow.rootViewController valueForKey:@"mainViewController"] isKindOfClass:([UITabBarController class])]){
            self.delegate = (id <SharedMesaageDelegate>)[(UINavigationController *)[(UITabBarController *)[rootWindow.rootViewController valueForKey:@"mainViewController"] selectedViewController] topViewController];
        }else{
            if([rootWindow.rootViewController isKindOfClass:([UINavigationController class])]){
                self.delegate = (id <SharedMesaageDelegate>)((UINavigationController *)rootWindow.rootViewController).topViewController;
            }else{
                self.delegate = (id <SharedMesaageDelegate>)rootWindow.rootViewController;
            }
        }
    }
    
    //存储分享信息
    self.shareMsgModel = nil;
    DLWWeChatShareMsgModel *msgModel = [[DLWWeChatShareMsgModel alloc] init];
    msgModel.title = title;
    msgModel.content = content;
    msgModel.mediaURL = url;
    msgModel.thumbURL = thumbURL;
    self.shareMsgModel = msgModel;
    [UMSocialUIManager setShareMenuViewDelegate:self];
    __weak typeof(self) weakSelf = self;
    //添加默认分享平台
#if 0
    [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_WechatSession),@(UMSocialPlatformType_WechatTimeLine)]];
#else
    [self dl_shareAddCustomePlatform:DLWWeChatShareCustomPlatformTypeQiyeWeChat iconImage:[UIImage imageNamed:@"wwechat_logo"] platformName:@"企业微信"];
#endif
    if([self.delegate respondsToSelector:@selector(dl_shareCustomeConfigCheck:)]){
        [self.delegate dl_shareCustomeConfigCheck:self];
    }
    
    if (self.customWxShareUI) {
        [self handleShareActionWithPlatformType:DLWWeChatShareCustomPlatformTypeQiyeWeChat userInfo:nil];
        return;
    }
    
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        if(platformType == UMSocialPlatformType_WechatSession || platformType == UMSocialPlatformType_WechatTimeLine){
            // 根据获取的platformType确定所选平台进行下一步操作
            //创建分享消息对象
            UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
            //创建网页内容对象
            UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:title descr:content thumImage:thumbURL];
            //设置网页地址
            shareObject.webpageUrl = url;
            //分享消息对象设置分享内容对象
            messageObject.shareObject = shareObject;
            //调用分享接口
            [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:weakSelf.delegate completion:^(id data, NSError *error) {
                [weakSelf handleMessageBack:data error:error];
            }];
        }else{
            self.currentType = platformType;
            //自定义分享平台
            [weakSelf handleShareActionWithPlatformType:platformType userInfo:userInfo];
        }
    }];
}

- (void)dl_shareWithMediaURL:(NSString *)url
                     thumbURL:(NSString *)thumbURL
                        title:(NSString *)title
                      content:(NSString *)content{
    [self dl_shareToWX:UMSocialPlatformType_WechatSession withMediaURL:url thumbURL:thumbURL title:title content:content];
}

- (void)dgg_shareImageToWXPlatformImage:(UIImage *)image{
    DLWWeChatShareMsgModel *msgModel = [[DLWWeChatShareMsgModel alloc] init];
    msgModel.shareImage = image;
    
    WWKSendMessageReq *req = [self requestObjectWithMessageModel:msgModel];
    [WWKApi sendReq:req];
}

- (WWKSendMessageReq *)requestObjectWithMessageModel:(DLWWeChatShareMsgModel *)shareMsgModel{
    WWKMessageImageAttachment *attachment = [[WWKMessageImageAttachment alloc] init];
    // 示例用图片，请填写你想分享的实际图片路径和名称
    attachment.filename = @"图片名称";//传图片时不必传
    attachment.path = @"图片路径";//传图片时不必传
    if(shareMsgModel.thumbURL){
        NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:shareMsgModel.thumbURL]];
        UIImage *thumbImg = [UIImage imageWithData:imgData];
        //缩略图不能超过32KB
        attachment.data = UIImagePNGRepresentation([self compressImageSize:thumbImg toByte:32*1024]);
    }
    if(shareMsgModel.shareThumbImage){
        //缩略图不能超过32KB
        attachment.data = UIImagePNGRepresentation([self compressImageSize:shareMsgModel.shareThumbImage toByte:32*1024]);
    }
    if (shareMsgModel.shareImage) {
        //分享图片不能超过10M
        UIImage *compressionImg = [self compressImageSize:shareMsgModel.shareImage toByte:10*1024*1024];
        NSData *data = UIImagePNGRepresentation(compressionImg);
        attachment.data = data;
    }
    WWKSendMessageReq *req = [[WWKSendMessageReq alloc] init];
    req.attachment = attachment;
    return req;
}


#pragma mark - 分享处理
- (void)handleShareActionWithPlatformType:(DLWWeChatShareCustomPlatformType)platformType userInfo:(NSDictionary *)userInfo{
    if(platformType == DLWWeChatShareCustomPlatformTypeQiyeWeChat){
        WWKSendMessageReq *req = [[WWKSendMessageReq alloc] init];
        WWKMessageLinkAttachment *attachment = [[WWKMessageLinkAttachment alloc] init];
        attachment.title = self.shareMsgModel.title;
        attachment.summary = self.shareMsgModel.content;
        attachment.url = self.shareMsgModel.mediaURL;
        if(self.shareMsgModel.shareThumbImage){
            if([self.shareMsgModel.shareThumbImage isKindOfClass:([UIImage class])]){
                attachment.icon = UIImageJPEGRepresentation(self.shareMsgModel.shareThumbImage, 1);
            }else if ([self.shareMsgModel.shareThumbImage isKindOfClass:([NSData class])]){
                attachment.icon = (NSData *)self.shareMsgModel.shareThumbImage;
            }else{
                //缩略图格式有误
            }
        }
        if(self.shareMsgModel.thumbURL){
            attachment.iconurl = self.shareMsgModel.thumbURL;
        }
        req.attachment = attachment;
        [WWKApi sendReq:req];
    }else{
        if([self.delegate respondsToSelector:@selector(dl_shareCustomePlatform:withUserInfo:)]){
            [self.delegate dl_shareCustomePlatform:platformType withUserInfo:userInfo];
        }
    }
}

- (BOOL)dl_handleOpenURL:(NSURL *)theURL{
    return [WWKApi handleOpenURL:theURL delegate:self];
}

#pragma mark - 处理自定义分享结果回调
- (void)onResp:(WWKBaseResp *)resp {
    if(self.currentType == DLWWeChatShareCustomPlatformTypeQiyeWeChat){
        [self handleWorkWechatResp:resp];
    }else{
        [self handleWorkWechatResp:resp];
    }
}

#pragma mark - 企业微信分享回调
- (void)handleWorkWechatResp:(WWKBaseResp *)resp{
    /*! @brief 所有通过sendReq发送的SDK请求的结果都在这个函数内部进行异步回调
     * param resp SDK处理请求后的返回结果 需要判断具体是哪项业务的回调
     */
    NSMutableString *extra = [NSMutableString string];
    /* 选择联系人的回调 */
    if ([resp isKindOfClass:[WWKPickContactResp class]]) {
        WWKPickContactResp *r = (WWKPickContactResp *)resp;
        for (int i = 0; i < MIN(r.contacts.count, 5); ++i) {
            if (extra.length) [extra appendString:@"\n"];
            [extra appendFormat:@"%@<%@>", [r.contacts[i] name], [r.contacts[i] email]];
        }
        if (r.contacts.count > 5) {
            [extra appendString:@"\n…"];
        }
    }
    /* SSO的回调 */
    if ([resp isKindOfClass:[WWKSSOResp class]]) {
        WWKSSOResp *r = (WWKSSOResp *)resp;
        [extra appendFormat:@"%@ for %@", r.code, r.state];
    }
    [self handleResultWithSuccess:(resp.errCode == 0) errorCode:resp.errCode platformType:DLWWeChatShareCustomPlatformTypeQiyeWeChat withErrorStr:resp.errStr];
}

#pragma mark - 友盟分享结果处理
- (void)handleMessageBack:(id)data error:(NSError *)error{
    self.shareMsgModel = nil;
    if (error) {
        NSLog(@"友盟分享失败：%@",error);
        if(self.dl_sharedMessageCallBack){
            self.dl_sharedMessageCallBack(NO, data, error);
        }
        if([self.delegate respondsToSelector:@selector(dl_sharedMessageCallBack:responseData:error:)]){
            [self.delegate dl_sharedMessageCallBack:NO responseData:data error:error];
        }
    }else{
        if ([data isKindOfClass:[UMSocialShareResponse class]]) {
            UMSocialShareResponse *resp = data;
            NSLog(@"友盟分享返回数据：%@，第三方应用返回原始数据：%@",resp.message,resp.originalResponse);
            if(self.dl_sharedMessageCallBack){
                self.dl_sharedMessageCallBack(YES, resp, error);
            }
            if([self.delegate respondsToSelector:@selector(dl_sharedMessageCallBack:responseData:error:)]){
                [self.delegate dl_sharedMessageCallBack:YES responseData:resp error:error];
            }
        }else{
            NSLog(@"友盟分享返回数据：%@",data);
            if(self.dl_sharedMessageCallBack){
                self.dl_sharedMessageCallBack(YES, data, error);
            }
            if([self.delegate respondsToSelector:@selector(dl_sharedMessageCallBack:responseData:error:)]){
                [self.delegate dl_sharedMessageCallBack:YES responseData:data error:error];
            }
        }
    }
}

#pragma mark - 处理结果回调
- (void)handleResultWithSuccess:(BOOL)success errorCode:(int)errorCode platformType:(DLWWeChatShareCustomPlatformType)type withErrorStr:(NSString *)errorStr{
    UMSocialShareResponse *response = [UMSocialShareResponse new];
    response.platformType = type;
    response.message = errorStr;
    if(self.dl_sharedMessageCallBack){
        self.dl_sharedMessageCallBack(success, response, nil);
    }
    if([self.delegate respondsToSelector:@selector(dl_sharedMessageCallBack:responseData:error:)]){
        [self.delegate dl_sharedMessageCallBack:success responseData:response error:nil];
    }
    
    WWXShareCallBackStatusType statusType;
    if (errorCode == 0) {
        statusType = WWXShareCallBackStatusTypeSuccess;
    }else if (errorCode == 1){
        statusType = WWXShareCallBackStatusTypeCancel;
    }else{
        statusType = WWXShareCallBackStatusTypeFail;
    }
    ///带状态回调
    if ([self.delegate respondsToSelector:@selector(dl_wwxsharedMessageCallBackStatusType:responseData:error:)]) {
        [self.delegate dl_wwxsharedMessageCallBackStatusType:statusType responseData:response error:nil];
    }
    if (self.dl_shareMessageWithStatusCallBack) {
        self.dl_shareMessageWithStatusCallBack(statusType, response, nil);
    }
}

#pragma mark - Methods
- (void)dl_shareAddCustomePlatform:(DLWWeChatShareCustomPlatformType)platformType iconImage:(UIImage *)iconImage platformName:(NSString *)platformName{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wenum-conversion"
    
    [UMSocialUIManager addCustomPlatformWithoutFilted:platformType withPlatformIcon:iconImage withPlatformName:platformName];
    
#pragma clang diagnostic pop
}

#pragma mark - UMSocialShareMenuViewDelegate
- (void)UMSocialShareMenuViewDidAppear{
    [self handMenuViewDisPlay:YES];
}

- (void)UMSocialShareMenuViewDidDisappear{
    [self handMenuViewDisPlay:NO];
}

- (void)handMenuViewDisPlay:(BOOL)isShow{
    if(self.dl_sharedMenuViewDisPlayBlock){
        self.dl_sharedMenuViewDisPlayBlock(isShow);
    }
    if([self.delegate respondsToSelector:@selector(dl_sharedMenuViewDisPlay:)]){
        [self.delegate dl_sharedMenuViewDisPlay:isShow];
    }
}

#pragma mark - 压缩图片
//压缩图片到指定大小内
- (UIImage *)compressImageSize:(UIImage *)image toByte:(NSUInteger)maxLength
{
    //首先判断原图大小是否在要求内，如果满足要求则不进行压缩，over
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxLength) return image;
    //原图大小超过范围，先进行“压处理”，这里 压缩比 采用二分法进行处理，6次二分后的最小压缩比是0.015625，已经够小了
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    //判断“压处理”的结果是否符合要求，符合要求就over
    UIImage *resultImage = [UIImage imageWithData:data];
    if (data.length < maxLength) return resultImage;
    
    //缩处理，直接用大小的比例作为缩处理的比例进行处理，因为有取整处理，所以一般是需要两次处理
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        //获取处理后的尺寸
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio)));
        //通过图片上下文进行处理图片
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        //获取处理后图片的大小
        data = UIImageJPEGRepresentation(resultImage, compression);
    }
    
    return resultImage;
}

@end
